<template>
  <view class="container">
    <view class="title">图片下载演示</view>
    
    <!-- 下载进度显示（处理异常值） -->
    <view class="progress">下载进度：{{ downloadProgress }}%</view>
    
    <!-- 下载后的图片显示 -->
    <view v-if="imagePath" class="image-wrap">
      <image :src="imagePath" mode="widthFix" class="show-image" />
    </view>
    
    <!-- 下载按钮 -->
    <button @click="downloadImage" class="download-btn" :disabled="isDownloading">
      {{ isDownloading ? '下载中...' : '下载图片' }}
    </button>
  </view>
</template>

<script>
export default {
  data() {
    return {
      imageUrl: "https://cdn.pixabay.com/photo/2020/05/04/14/14/cat-5129332_960_720.jpg",
      imagePath: "",
      downloadProgress: 0,
      isDownloading: false
    };
  },
  methods: {
    downloadImage() {
      this.isDownloading = true;
      this.downloadProgress = 0;
      this.imagePath = "";

      const downloadTask = uni.downloadFile({
        url: this.imageUrl,
        success: (res) => {
          if (res.statusCode === 200) {
            this.imagePath = res.tempFilePath;
            console.log("图片下载完成，临时路径：", res.tempFilePath);
          } else {
            uni.showToast({ title: "下载失败", icon: "none" });
            this.downloadProgress = 0;
          }
        },
        fail: (err) => {
          console.error("图片下载失败：", err);
          uni.showToast({ title: "网络请求失败", icon: "none" });
          this.downloadProgress = 0;
        },
        complete: () => {
          this.isDownloading = false;
        }
      });

      // 监听进度（处理异常值）
      downloadTask.onProgressUpdate((res) => {
        const validProgress = isFinite(res.progress) 
          ? Math.min(Math.max(res.progress, 0), 100) 
          : 0;
        this.downloadProgress = validProgress;
      });
    }
  }
};
</script>

<style scoped>
.container {
  padding: 30rpx;
  text-align: center;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  margin: 40rpx 0;
}

.progress {
  font-size: 28rpx;
  margin: 20rpx 0;
}

.image-wrap {
  margin: 30rpx 0;
  padding: 20rpx;
}

.show-image {
  width: 80%;
  border-radius: 10rpx;
}

.download-btn {
  width: 60%;
  height: 80rpx;
  line-height: 80rpx;
  font-size: 28rpx;
}
</style>